package xyz.labmem.main.modular.app.indexShow.service.impl

import cn.hutool.core.util.ClassUtil
import com.baomidou.mybatisplus.annotation.TableField
import com.baomidou.mybatisplus.annotation.TableName
import io.swagger.annotations.Api
import io.swagger.annotations.ApiModelProperty
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.RequestMapping
import xyz.labmem.base.core.annotion.DynamicPageColumn
import xyz.labmem.base.core.annotion.SocketPath
import xyz.labmem.base.core.annotion.SqlColumn
import xyz.labmem.base.core.tool.getClassAllField
import xyz.labmem.base.core.tool.isNotNull
import xyz.labmem.base.sys.base.BaseController
import xyz.labmem.base.sys.consts.PathPrefixConst
import xyz.labmem.main.modular.app.indexShow.controller.response.GlobalRes
import xyz.labmem.main.modular.app.indexShow.controller.response.ModuleRes
import xyz.labmem.main.modular.app.indexShow.controller.response.TableEntiy
import xyz.labmem.main.modular.app.indexShow.service.AppShowAmountService
import xyz.labmem.main.modular.app.other.entity.SysUserMenus
import xyz.labmem.main.modular.app.other.mapper.sysUserMenus1Mapper
import xyz.labmem.main.modular.app.zhgk.mapper.App_zhgfdywyhbsjgcjb_Mapper

/**
 * @Author lty
 * @Date 2022/1/5 15:24
 */
@Service
class AppShowAmountServiceImpl(
    private var appZhgfdywyhbsjgcjbMapper: App_zhgfdywyhbsjgcjb_Mapper,
    private var sysUserMenusMapper: sysUserMenus1Mapper
) : AppShowAmountService {

    override fun getAmountByModel(pack: String, isChart : Boolean): ArrayList<ModuleRes> {
        var user = BaseController.getLoginUser()
        var menus = sysUserMenusMapper.selectListAll(user.id)
        val res = ArrayList<ModuleRes>()
        var classs = ClassUtil.scanPackage("${pack}.entity")
        var a = ""
        for(it in classs){
            //获取controller
            if("${pack}.entity" == it.packageName){
                val contr = Class.forName("${pack}.controller.${it.simpleName}_Controller")
                val api = contr.getAnnotation(Api::class.java)
                val req = contr.getAnnotation(RequestMapping::class.java)
                val table = it.getAnnotation(TableName::class.java)
                val open = it.getAnnotation(SocketPath::class.java)
                var longitude = false
                var latitude = false
                a = a + "SELECT '"+table.value+"' table_name,COUNT(1) table_comment FROM  "+table.value+ " UNION "
                var isShow = false
                var prefix = req.value[0].replace(PathPrefixConst.APP_PATH_PREFIX, "")

                if(menus.contains(SysUserMenus().apply { userId=user.id;menuId=prefix }) || user.superr==1){
                    isShow = true
                }
                it.declaredFields.forEach { that ->
                    if(that.name == "jd")
                        longitude = true
                    if (that.name == "wd")
                        latitude = true
                }

                res.add(ModuleRes().apply {
                    name = api.tags[0]
                    this.prefix = prefix
                    this.table = table.value
                    hasPoint = latitude and longitude
                    openType = open?.value == "true"
                    issub = open?.issub == true
                    index = open?.order?:1
                    this.isChart = isChart
                    this.enShow = isShow
                    tu= open.isChart
                    yitu = open.yjChart
                    ziTu = open.isSubChart
                })
            }
        }
        var tables = appZhgfdywyhbsjgcjbMapper.selectTableCount(a.substring(0,a.length-6))
        for(re in res){
            re.num = tables.get(tables.indexOf(TableEntiy().apply { tableName= re.table })).tableComment
        }
        if(isChart){
            res.sortByDescending { user -> user.num }
        }else{
            res.sortBy { user -> user.index }
        }

        return res
    }

    override fun getAmount(pack: String,packName: String,value: String): ArrayList<GlobalRes> {
        var user = BaseController.getLoginUser()
        var menus = sysUserMenusMapper.selectListAll(user.id)
        val res = ArrayList<GlobalRes>()
        var classs = ClassUtil.scanPackage("${pack}.entity")
        for(it in classs){
            //获取controller
            if("${pack}.entity" == it.packageName){
                val contr = Class.forName("${pack}.controller.${it.simpleName}_Controller")
                val req = contr.getAnnotation(RequestMapping::class.java)
                var prefix = req.value[0].replace(PathPrefixConst.APP_PATH_PREFIX, "")
                if(menus.contains(SysUserMenus().apply { userId=user.id;menuId=prefix }) || user.superr==1){
                    val fields = it.declaredFields
                    val table = it.getAnnotation(TableName::class.java)
                    val socketPath = it.getAnnotation(SocketPath::class.java)
                    val api = contr.getAnnotation(Api::class.java)
                    var columns = ArrayList<String>()
                    var unitName = ""
                    for(field in fields){
                        val sqlColumn = field.getAnnotation(SqlColumn::class.java)
                        val tableField = field.getAnnotation(TableField::class.java)
                        if(sqlColumn!=null && tableField!=null){
                            if(sqlColumn.unit){
                                unitName = tableField.value
                            }
                            columns.add(tableField.value)
                        }
                    }
                    var c = "SELECT id,'"+packName+"' type1,'"+ api.tags[0] +"' type2,'"+prefix+ "' prefix,"
                    var w = " where "
                    var i = 1
                    if(unitName.length>0){
                        c = c + unitName + " unit,"
                    }
                    if(socketPath!=null && socketPath.issub){
                        c = c +"'true' sub,"
                    }
                    for(column in columns){
                        c = c + "CASE "+column+" like '%"+value+"%' WHEN '1' THEN "+column+" ELSE null END 'value"+i+"', "
                        if(i!=1){
                            w = w +" or "
                        }
                        w = w +column +" like '%"+ value +"%'"
                        i++
                    }
                    if(columns.size>0){
                        c = c.substring(0,c.length-2) + " from " + table.value + w
                        res.addAll(appZhgfdywyhbsjgcjbMapper.selectTable(c))
                    }
                }
            }
        }
        return res
    }
}